package com.ow.dva.module.base.controller;

import com.ow.dva.module.base.entity.json.RT;
import com.ow.dva.module.base.service.ImageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 描述 : 图片处理 Controller
 * 包名 : com.ow.dva.controller
 * 作者 : GaoXiang
 * 时间 : 18-11-8
 * 版本 : V1.0
 */
@Api(tags = "图片相关")
@Controller
@RequestMapping("/image")
public class ImageController extends BaseController {

    /**
     * 文件上传
     * @param imageFile 图片
     * @return 上传状态
     */
    @ApiOperation(value = "上传图片",notes = "表单提交图片")
    @PostMapping(value = "/upload")
    @ResponseBody
    public RT imageUpload(MultipartFile imageFile) throws IOException {
        if(imageFile != null && !imageFile.isEmpty()){
            try {
                String filePath = imageService.imageFileUpload(imageFile);
                return RT.ok("上传成功!",filePath);
            } catch (IOException e) {
                //e.printStackTrace();
                logger.error("图片上传失败：" + e.getMessage());
                return RT.error(RT.ERROR_0101,"图片上传失败!");
            }
        }else{
            return RT.error(RT.ERROR_0102,"没有选择上传文件!");
        }
    }

 

    /**
     * 下载图片
     * @param src 图片地址
     */
    @ApiOperation(value = "图片下载",notes = "根据地址下载图片")
    @GetMapping("/down")
    public void imageDown(String src, HttpServletResponse response) throws IOException {
        String staticPath = imageService.getStaticPath("/upload");
        imageService.downFile(response,staticPath + src);
    }

    @Resource
    private ImageService imageService;
}
